package com.itmck.filter;

import com.alibaba.fastjson.JSON;
import com.itmck.bo.ApiResultResponse;
import com.itmck.component.DynamicRouteServiceImplByNacos;
import com.itmck.util.UrlCheckUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;


/**
 * 太阳当空照,花儿对我笑
 * <p>
 * Create by M ChangKe 2021/11/3 16:42
 * <p>
 * 自定义全局过滤器,实现过滤功能
 **/
@Component
public class AuthFilter implements GlobalFilter {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        String path = exchange.getRequest().getURI().getPath();//获取路径
        List<String> skipUrls = DynamicRouteServiceImplByNacos.SKIP_URLS;
        if (UrlCheckUtils.checkUrl(skipUrls, path)) {
            return chain.filter(exchange);
        }else{
            ApiResultResponse<String> data;
            List<String> blackUrls = DynamicRouteServiceImplByNacos.BLACK_URLS;
            if (UrlCheckUtils.checkUrl(blackUrls, path)){
                //存在黑名单中直接警告
                data = ApiResultResponse.error("无法请求黑名单", "401");
            }else{
                String token = exchange.getRequest().getHeaders().getFirst("token");
                if ("token".equals(token)) {
                    return chain.filter(exchange);
                }
                data = ApiResultResponse.error("非法请求", "401");
            }
            byte[] bytes = JSON.toJSONBytes(data);
            ServerHttpResponse response = exchange.getResponse();
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }

    }
}